
/**
 * @class Kohive.controllers.IdCardsController
 * @extends Kohive.controllers.KohiveController
 * Manages the Id Card model
 */
Kohive.controllers.IdCardsController = Ext.extend(
		Kohive.controllers.KohiveController, {
			title			: Ext.ux.Translator.translate('app_id_card'),

			constructor		: function() {
				Kohive.controllers.IdCardsController.superclass.constructor
						.call(this, {
									viewsPackage	: Kohive.views.idcards
								});

				this.initEvents();
				this.initListeners();

				this.on('read', this.edit, this);

				// TODO: This is a relic of old MVC, remove it once on ExtMVC 0.6 or above
				// TODO: DIRTY HACK to get the id of the id card using os params
				this.registerAction('show', function(idCard) {
							if (idCard && typeof idCard == "object")
								return this.fireEvent('read', idCard);

							var id = Kohive.OS.params.id;
							if (!id)
								return;

							this.read(id);
						});
			},

			/**
			 * Attempts to load all Id Cards for the current user.
			 * Fires the 'index' event if successful
			 * @param {Ext.Component} view An optional view component that this controller should listen to
			 * @return {Ext.data.Store} The store containing Id Cards.  This won't be loaded yet but may
			 * be useful to UI elements which are bound to a store
			 */
			index			: function(view) {
				if (typeof view != 'undefined' && view != null) {
					view.on({
								scope		: this,
								'use'		: this.use,
								'destroy'	: this.destroy,
								'verify'	: this.verify,
								'add'		: this.build,
								'edit'		: this.edit
							});
				}

				return Kohive.models.IdCard.findAll({
							scope		: this,
							url			: this.scopedUrl("id_cards"),
							listeners	: {
								scope			: this,
								load			: function(idCards) {
									this.fireEvent('index', idCards);
								},
								loadexception	: function() {
									this.fireEvent('index-failed');
								}
							}
						});
			},

			/**
			 * Displays the New Id Card form and listens to events on it
			 */
			build			: function() {
				if (typeof this.newIdCardWindow == 'undefined') {
					this.newIdCardWindow = this.renderView('new', {
								closeAction	: 'hide',
								autoShow	: true,
								listeners	: {
									scope	: this,
									'save'	: this.create
								}
							});
				}

				this.newIdCardWindow.show();
			},

			/**
			 * Opens the edit window for a particular Id Card
			 * @param {Kohive.models.IdCard} idCard The Id Card to edit
			 */
			edit			: function(idCard) {
				var key = String.format("show-{0}", idCard.get('id'));

				this.editIdCardWindow = this.renderView('show', {
							idCard			: idCard,
							autoShow		: true,
							listeners		: {
								scope				: this,
								'update'			: this.update,
								'upload-complete'	: this.fireEvent
										.createDelegate(this, ['update'])
							},
							viewCacheKey	: key
						});

				// this.editIdCardWindow.show();
			},

			/**
			 * Attempts to create a new Id Card
			 * @param {Object} data A fields object (e.g. {title: 'My Id Card'})
			 * @param {Ext.form.BasicForm} form The BasicForm from which to take values.  If supplied this
			 * will be used instead of the data argument and a fileUpload Ajax request sent
			 */
			create			: function(data, form) {
				var idCard = new Kohive.models.IdCard(data);

				idCard.save({
							scope	: this,
							// isUpload: true,
							form	: typeof form == 'undefined' ? null : form
									.getEl(),
							url		: this.scopedUrl("id_cards"),
							success	: function(idCard, response) {
								this.fireEvent('create', idCard);
							},
							failure	: function(idCard, response) {
								this.fireEvent('create-failed', idCard);
							}
						});
			},

			/**
			 * Attempts to find (read) a single ID card
			 * @param {Number} id The Id of the ID Card to read
			 */
			read			: function(id) {
				Kohive.models.IdCard.findById(id, {
					scope	: this,
					url		: this.scopedUrl(String.format("id_cards/{0}", id)),
					success	: function(idCard) {
						this.fireEvent('read', idCard);
					},
					failure	: function() {
						this.fireEvent('read-failed', id);
					}
				}
				);
			},

			/**
			 * Attempts to update an existing Id Card with new values
			 * @param {Kohive.models.IdCard} idCard The existing Id Card object
			 * @param {Object} updates An object containing updates to apply to the Id Card
			 */
			update			: function(idCard, updates, forceRefresh) {
				for (var key in updates) {
					idCard.set(key, updates[key]);
				};

				idCard.save({
					scope	: this,
					url		: this.scopedUrl(String.format("id_cards/{0}",
							idCard.get('id')
					)),
					success	: function() {
						this.fireEvent('update', idCard, updates, forceRefresh);
					},
					failure	: function() {
						this.fireEvent('update-failed', idCard, updates);
					}
				}
				);
			},

			/**
			 * Attempts to destroy an existing Id Card
			 * @param {Kohive.models.IdCard} idCard The Id Card instance to destroy
			 */
			destroy			: function(idCard) {
				// TODO: for some reason this is being called by the event 'destroy' when closing the settings
				// app. the only way around it is to check if idCard.get is defined. don't know what
				// is causing it :/
				if (!idCard || !idCard.get)
					return;

				idCard.destroy({
							scope	: this,
							url		: this.scopedUrl(String.format(
									"id_cards/{0}", idCard.get('id')
							)),
							success	: function() {
								this.fireEvent('destroy', idCard);
							},
							failure	: function() {
								this.fireEvent('destroy-failed', idCard);
							}
						});
			},

			/**
			 * Attempts to mark an Id Card as the one to use in the current hive
			 * @param {Kohive.models.IdCard} idCard The Id Card to use
			 */
			use				: function(idCard) {
				var mem = Kohive.OS.getCurrentHive(); // returns the current membership :/
				mem.set('id_card_id', idCard.get('id'));

				mem.save({
							scope	: this,
							success	: function() {
								this.fireEvent('hive-id-card-update', idCard);
							},
							failure	: function() {
								this.fireEvent('hive-id-card-update-failed',
										idCard
								);
							}
						});
			},

			/**
			 * Attempts to verify an id cards email address
			 */
			verify			: function(idCard) {
				idCard.save({
							scope	: this,
							url		: this.scopedUrl('verify'),
							success	: function() {
								this.fireEvent('verify-success');
							},
							failure	: function() {
								this.fireEvent('verify-failed');
							}
						});
			},

			/**
			 * Sets up listeners on a view element.
			 */
			initListeners	: function() {
				Ext.getCmp('memberOptions').on({
					scope			: this,
					'show-idcard'	: function(id) {
						Kohive.models.IdCard.findById(id, {
									scope	: this,
									url		: this.scopedUrl(String.format(
											"id_cards/{0}", id
									)),
									success	: function(idCard) {
										this.edit(idCard);
									}
								});
					}
				}
				);
			},

			/**
			 * Sets up events emitted by this 
			 */
			initEvents		: function() {
				this.addEvents(
						/**
				 * @event create
				 * Fired when a new Id Card has been successfully created
				 * @param {Kohive.models.IdCard} idCard The newly created Id Card
				 */
						'create',

						/**
						 * @event create-failed
						 * Fired when an attempt to create a new Id Card failed
						 * @param {Kohive.models.IdCard} idCard The idCard object which couldn't be saved
						 */
						'create-failed',

						/**
						 * @event read
						 * Fired when a single Id Card has been loaded from the database
						 * @param {Kohive.models.IdCard} idCard The Id Card instance that was loaded
						 */
						'read',

						/**
						 * @event read-failed
						 * Fired when an attempt to load a single Id Card failed
						 * @param {Number} id The ID of the Id Card we were attempting to find
						 */
						'read-failed',

						/**
						 * @event update
						 * Fired when an existing Id Card has been successfully created
						 * @param {Kohive.models.IdCard} idCard The updated Id Card
						 * @param {Object} updates The updates object that was supplied
						 */
						'update',

						/**
						 * @event update-failed
						 * Fired when an attempty to update an existing Id Card failed
						 * @param {Kohive.models.IdCard} idCard The Id Card we were attempting to update
						 * @param {Object} updates The object of updates we were trying to apply
						 */
						'update-failed',

						/**
						 * @event destroy
						 * Fired when an existing Id Card has been successfully destroyed
						 * @param {Kohive.models.IdCard} idCard The Id Card that was destroyed
						 */
						'destroy',

						/**
						 * @event destroy-failed
						 * Fired when an attempt to destroy an existing Id Card failed
						 * @param {Kohive.models.IdCard} idCard The Id Card we were trying to destroy
						 */
						'destroy-failed',

						/**
						 * @event index
						 * Fired when an Id Cards collection has been loaded from the database
						 * @param {Ext.data.Store} idCards An Ext.data.Store containing the Id Cards retrieved
						 */
						'index',

						/**
						 * @event index-failed
						 * Fired when an error was encountered while trying to load the Id Cards from the database
						 */
						'index-failed',

						/**
						 * @event hive-id-card-update
						 * Fired when the Id Card used in the current hive has been successful updated.  This is fired
						 * by the 'use' action if the save went through correctly
						 * @param {Kohive.models.IdCard} idCard The Id Card now being used for the current Hive
						 */
						'hive-id-card-update',

						/**
						 * @event hive-id-card-update-failed
						 * Fired if the user wanted to update the Id Card used in the current Hive but the operation failed
						 * @param {Kohive.models.IdCard} idCard The Id Card the user wanted to set
						 */
						'hive-id-card-update-failed',

						/**
						 * @event verify-success
						 * Fires if verify request is successful
						 */
						'verify-success',

						/**
						 * @event verify-failed
						 * Fires if the verify request fails
						 */
						'verify-failed'
				);
			}
		}
);

ExtMVC.OS.getOS().registerController('idcards',
		Kohive.controllers.IdCardsController
);